package cn.wbnyua.resume.mvc.service.v2;

import cn.wbnyua.resume.mvc.domain.Award;
import cn.wbnyua.resume.mvc.domain.Projects;
import cn.wbnyua.resume.mvc.mapper.ProjectsMapper;
import cn.wbnyua.resume.util.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 作者：wbnyua.
 * 创建时间: 2023/2/6 22:02.
 */

@Service
public class ProjectsService {
    @Autowired
    private ProjectsMapper mapper;
    @Autowired
    private RedisUtil redisUtil;
    private static final String REDIS_KEY_LIST = "projectsList";
    private static final String REDIS_KEY_ONE = "projects_";

    public List<Projects> findAll(){
        Object result = redisUtil.get(REDIS_KEY_LIST);
        if (result!=null){
            return JSONObject.parseArray(result.toString(), Projects.class);
        }
        List<Projects> list = mapper.findAll();
        redisUtil.set(REDIS_KEY_LIST,JSONObject.toJSONString(list));
        redisUtil.expire(REDIS_KEY_LIST,3600);
        return list;
    }

    public Projects findById(Long id){
        String key = REDIS_KEY_LIST + id;
        Object redisResult = redisUtil.get(key);
        if (redisResult != null){
            return (Projects) redisResult;
        }
        Projects projects = mapper.findById(id);
        redisUtil.set(key,projects);
        return projects;
    }

    public int add(Projects projects){
        int result = mapper.add(projects);
        if (result > 0){
            String key = REDIS_KEY_ONE+projects.getId();
            redisUtil.set(key,projects);
        }
        return result;
    }
    public int update(Projects projects){
        int result = mapper.update(projects);
        if (result > 0){
            String key = REDIS_KEY_ONE+projects.getId();
            redisUtil.set(key,projects);
        }
        return result;
    }

    public int remove(Long id){
        int result = mapper.remove(id);
        if (result > 0){
            redisUtil.del(REDIS_KEY_ONE+id);
            redisUtil.del(REDIS_KEY_LIST);
        }
        return result;
    }
}
